<template>
  <div class="direction-comparison">
    <div ref="radarChartRef" class="chart-container"></div>
    
    <el-row :gutter="20" class="mt20">
      <el-col :span="24">
        <el-table :data="comparisonData" style="width: 100%" border>
          <el-table-column prop="directionName" label="方向名称" align="center" />
          <el-table-column prop="avgCourseScore" label="平均课程学习分" align="center" />
          <el-table-column prop="avgTimeScore" label="平均学习时长" align="center">
            <template #default="scope">
              {{ formatMinutesToHours(scope.row.avgTimeScore) }}
            </template>
          </el-table-column>
          <el-table-column prop="avgCompetitionScore" label="平均竞赛情况分" align="center" />
          <el-table-column prop="avgProjectScore" label="平均项目实践分" align="center" />
          <el-table-column prop="avgInnovationScore" label="平均科创贡献分" align="center" />
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import * as echarts from 'echarts'

// 定义props
const props = defineProps({
  logList: {
    type: Array,
    default: () => []
  },
  directionList: {
    type: Array,
    default: () => []
  }
})

// 图表实例
const radarChartRef = ref(null)
let radarChartInstance = null

// 选中的方向
const selectedDirections = ref([])

// 将分钟数转换为"X小时Y分钟"格式
const formatMinutesToHours = (minutes) => {
  if (!minutes && minutes !== 0) return '0分钟'
  
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  
  if (hours > 0 && mins > 0) {
    return `${hours}小时${mins}分钟`
  } else if (hours > 0) {
    return `${hours}小时`
  } else {
    return `${mins}分钟`
  }
}

// 计算方向对比数据
const calculateComparisonData = () => {
  // 初始化统计数据结构
  // 第一层：按direction字段对数据进行方向维度的区分
  const statsByDirection = {}
  
  // 初始化每个方向的数据结构
  props.directionList.forEach(direction => {
    statsByDirection[direction.id] = {
      directionId: direction.id,
      directionName: direction.directionName,
      studentCount: 0,
      students: new Set(), // 使用Set来统计不重复的学生
      // 第二层：在每个方向下，按logType字段区分不同的分析维度
      scoresByLogType: {
        0: 0, // 课程学习
        1: 0, // 学习时长
        2: 0, // 竞赛情况
        3: 0, // 项目实践
        4: 0  // 科创贡献
      }
    }
  })
  
  // 处理日志数据
  props.logList.forEach(log => {
    // 检查日志数据是否包含必要的字段
    if (!log.direction || log.logType === undefined || log.logType === null || log.score === undefined || log.score === null) {
      return
    }
    
    // 检查方向是否存在于统计数据中
    if (!statsByDirection[log.direction]) {
      // 如果方向不在列表中，跳过
      return
    }
    
    // 添加学生到Set中
    const studentKey = `${log.studentNumber}-${log.studentName}`
    statsByDirection[log.direction].students.add(studentKey)
    
    // 第三层：对每个方向下各分析维度对应的score值进行求和
    const scoreValue = parseFloat(log.score) || 0
    statsByDirection[log.direction].scoresByLogType[log.logType] += scoreValue
  })
  
  // 转换为数组并按方向ID排序
  const sortedDirections = Object.values(statsByDirection).sort((a, b) => a.directionId - b.directionId)
  
  // 计算平均值，并转换为表格所需格式
  const result = sortedDirections.map(item => {
    const studentCount = item.students.size
    const courseScore = item.scoresByLogType[0]
    const timeScore = item.scoresByLogType[1]
    const competitionScore = item.scoresByLogType[2]
    const projectScore = item.scoresByLogType[3]
    const innovationScore = item.scoresByLogType[4]
    
    // 计算平均值
    const avgCourseScore = studentCount > 0 ? courseScore / studentCount : 0
    const avgTimeScore = studentCount > 0 ? timeScore / studentCount : 0
    const avgCompetitionScore = studentCount > 0 ? competitionScore / studentCount : 0
    const avgProjectScore = studentCount > 0 ? projectScore / studentCount : 0
    const avgInnovationScore = studentCount > 0 ? innovationScore / studentCount : 0
    const avgTotalScore = avgCourseScore + avgTimeScore + avgCompetitionScore + avgProjectScore + avgInnovationScore
    
    return {
      directionId: item.directionId,
      directionName: item.directionName,
      studentCount,
      avgCourseScore: parseFloat(avgCourseScore.toFixed(2)),
      avgTimeScore: parseFloat(avgTimeScore.toFixed(2)),
      avgCompetitionScore: parseFloat(avgCompetitionScore.toFixed(2)),
      avgProjectScore: parseFloat(avgProjectScore.toFixed(2)),
      avgInnovationScore: parseFloat(avgInnovationScore.toFixed(2)),
      avgTotalScore: parseFloat(avgTotalScore.toFixed(2))
    }
  })
  
  return result
}

// 计算对比数据（用于表格显示）
const comparisonData = computed(() => {
  const allData = calculateComparisonData()
  
  // 如果没有选择方向，显示所有方向
  if (selectedDirections.value.length === 0) {
    return allData
  }
  
  // 否则只显示选中的方向
  return allData.filter(item => selectedDirections.value.includes(item.directionId))
})

// 处理方向选择变化
// const handleDirectionChange = () => {
//   nextTick(() => {
//     updateRadarChart()
//   })
// }

// 初始化雷达图
const initRadarChart = () => {
  if (radarChartRef.value) {
    radarChartInstance = echarts.init(radarChartRef.value)
    updateRadarChart()
  }
}

// 更新雷达图
const updateRadarChart = () => {
  if (!radarChartInstance) return
  
  const allData = calculateComparisonData()
  
  // 如果没有选择方向，默认显示所有方向
  let displayData = allData
  if (selectedDirections.value.length === 0 && allData.length > 0) {
    displayData = allData
    // 设置默认选中的方向
    selectedDirections.value = displayData.map(item => item.directionId)
  } else if (selectedDirections.value.length > 0) {
    displayData = allData.filter(item => selectedDirections.value.includes(item.directionId))
  }
  
  // 准备雷达图数据
  const indicator = [
    { name: '课程学习', max: 100 },
    { name: '学习时长', max: 10000 },
    { name: '竞赛情况', max: 100 },
    { name: '项目实践', max: 100 },
    { name: '科创贡献', max: 100 }
  ]
  
  const seriesData = displayData.map(item => ({
    name: item.directionName,
    value: [
      item.avgCourseScore,
      item.avgTimeScore,
      item.avgCompetitionScore,
      item.avgProjectScore,
      item.avgInnovationScore
    ]
  }))
  
  const option = {
    title: {
      text: '方向能力对比雷达图',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: 'bottom'
    },
    radar: {
      indicator: indicator,
      radius: '60%'
    },
    series: [{
      type: 'radar',
      data: seriesData
    }]
  }
  
  radarChartInstance.setOption(option, true)
}

// 调整图表大小
const resizeChart = () => {
  if (radarChartInstance) {
    radarChartInstance.resize()
  }
}

// 暴露方法给父组件
defineExpose({
  resizeChart
})

// 组件挂载时初始化
onMounted(() => {
  initRadarChart()
  window.addEventListener('resize', resizeChart)
})

// 监听数据变化，更新图表
watch(
  () => [props.logList, props.directionList],
  () => {
    nextTick(() => {
      updateRadarChart()
    })
  },
  { deep: true }
)
</script>

<style scoped>
.direction-comparison {
  width: 100%;
}

.chart-container {
  width: 100%;
  height: 500px;
}

.mt20 {
  margin-top: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
</style>